package com.etoak.service.impl;

import com.etoak.service.ILikeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

/**
 * @author Administrator
 * @version 1.0
 * @description: TODO
 * @date 2024/7/12 20:29
 */
@Service
public class LikeService implements ILikeService {
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public boolean addLike(Integer newsId, String username) {
        String key = "like:news:"+newsId;
        Boolean exist = redisTemplate.opsForHash().hasKey(key,username);
        if(exist){
            redisTemplate.opsForHash().delete(key,username);
        }else{
            redisTemplate.opsForHash().put(key,username, "true");
        }
        return !exist;
    }

    @Override
    public Integer count(Integer newsId) {
        String key = "like:news:"+newsId;

        return Math.toIntExact(redisTemplate.opsForHash().size(key));
    }
}
